package cn.zclong.student.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.itcast.jdbc.TxQueryRunner;
import cn.zclong.student.domain.Student;

/*
 * 与数据库交互
 */
public class StuDao {
	private QueryRunner qr = new TxQueryRunner();
	
	/*
	 * 添加报名学生
	 */
	public void addStu(Student stu) {		
		try {
			String sql = "insert into t_stu values(?,?,?,?,?)";
			Object[] param = {stu.getSid(), stu.getStuid(), stu.getStuname(), stu.getStuclass(), stu.getMajor()};
			qr.update(sql, param);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	/*
	 * 校验该学生是否报名
	 */
	public Student findByStuid(String stuid) {
		try {
			String sql = "select * from t_stu where stuid=?";
			return qr.query(sql, new BeanHandler<Student>(Student.class), stuid);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/*
	 * 管理员对学生的查询
	 */
	public List<Student> findAll() {
		try{
			String sql = "select * from t_stu";
			return qr.query(sql, new BeanListHandler<Student>(Student.class));
		}catch(SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/*
	 * 管理员对学生信息修改前的加载工作
	 */
	public Student load(String sid) {
		try{
			String sql = "select * from t_stu where sid=?";
			return qr.query(sql, new BeanHandler<Student>(Student.class), sid);
		}catch(SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/*
	 * 管理员对学生信息修改
	 */
	public void edit(Student student) {
		try {
			String sql = "update t_stu set stuid=?,stuname=?,stuclass=?,major=? where sid=?";
			qr.update(sql, student.getStuid(), student.getStuname(), student.getStuclass(), student.getMajor(), student.getSid());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/*
	 * 删除学生
	 */
	public void delete(String sid) {
		try{
			String sql = "delete from t_stu where sid=?";
			qr.update(sql, sid);
		}catch(SQLException e) {
			throw new RuntimeException(e);
		}		
	}
}
